from django.core.cache import cache
from rest_framework import request
from rest_framework.authentication import BaseAuthentication

from users.models import UserModel
from utils.errors import ParamsException


class UserAuthentication(BaseAuthentication):
    # 该方法必须被重写
    def authenticate(self, request):
        # 判断请求地址是登录和注册时，返回None 跳过中间件（验证）
        not_path = ['/api/user/changeinfopassword/', '/api/user/', '/api/user/register/', '/api/user/login/', '/api/user/send_message/', '/api/user/changepassword/']
        for path in not_path:
            if request.path == path:
                return None
        token = request.GET.get('token')\
                if request.GET.get('token')\
                else request.data.get('token')
        if not token:
            raise ParamsException({'code': 1006, 'msg': '用户认证失败'})
        user_id = cache.get(token)
        if not user_id:
            raise ParamsException({'code': 1006, 'msg': '用户认证失败'})
        user = UserModel.objects.filter(pk=user_id).first()
        return user, token
        # 相当于 request.user = user / request.token = token
